<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品型号" prop="fDeviceModel">
        <el-input v-model="queryParams.fDeviceModel" placeholder="请输入产品型号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="添加日期">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:product:add']">新增产品</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" prop="fId" />
      <el-table-column label="产品名称" align="center" prop="fProductName" width="150" />
      <el-table-column label="产品型号" align="center" prop="fDeviceModel" width="150" />
      <el-table-column label="产品尺寸" align="center" prop="fProductSize" />
      <el-table-column label="DPI" align="center" prop="fDpi" />
      <el-table-column label="可视区域(mm)" align="center" prop="fVisualNum" width="150" />
      <el-table-column label="分辨率" align="center" prop="fPower" />
      <el-table-column label="外观尺寸(mm)" align="center" prop="fDimensions" width="150" />
      <el-table-column label="基板类型" align="center" prop="fPlacodeType" />
      <el-table-column label="像素间距(mm)" align="center" prop="fPixel" width="150" />
      <el-table-column label="连接方式" align="center" prop="fConnectType" />
      <el-table-column label="IC芯片" align="center" prop="fIcChip" />
      <el-table-column label="工作电压(v)" align="center" prop="fVoltage" width="150" />
      <el-table-column label="工作温度(℃)" align="center" prop="fTemperature" width="150" />
      <el-table-column label="产品重量(g)" align="center" prop="fWeight" width="150" />
      <el-table-column label="模组类型" align="center" prop="wfModuleColor.fModuleName" />
      <el-table-column label="状态" align="center" prop="fForbidStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.fForbidStatus" />
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" prop="fCreaterName" />
      <el-table-column label="添加日期" align="center" prop="fCreateDate" width="180" />
      <el-table-column label="最后修改人" align="center" prop="fModifierName" width="100" />
      <el-table-column label="最后修改日期" align="center" prop="fModifyDate" width="180">
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, 1)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="65%">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="fProductName">
              <el-input v-model="form.fProductName" placeholder="请输入产品名称" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品型号" prop="fDeviceModel">
              <el-input v-model="form.fDeviceModel" placeholder="请输入产品型号" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="DPI" prop="fDpi">
              <el-input v-model="form.fDpi" placeholder="请输入DPI" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="可视区域(mm)" prop="fVisualNum">
              <el-input v-model="form.fVisualNum" placeholder="请输入可视区域(mm)" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分辨率" prop="fPower">
              <el-input v-model="form.fPower" placeholder="请输入分辨率" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="外观尺寸(mm)" prop="fDimensions">
              <el-input v-model="form.fDimensions" placeholder="请输入外观尺寸(mm)" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="基板类型" prop="fPlacodeType">
              <el-input v-model="form.fPlacodeType" placeholder="请输入基板类型" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="像素间距(mm)" prop="fPixel">
              <el-input v-model="form.fPixel" placeholder="请输入像素间距(mm)" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="连接方式" prop="fConnectType">
              <el-input v-model="form.fConnectType" placeholder="请输入连接方式" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="IC芯片" prop="fIcChip">
              <el-input v-model="form.fIcChip" placeholder="请输入IC芯片" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作电压(v)" prop="fVoltage">
              <el-input v-model="form.fVoltage" placeholder="请输入工作电压(v)" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作温度(℃)" prop="fTemperature">
              <el-input v-model="form.fTemperature" placeholder="请输入工作温度(℃)" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品重量(g)" prop="fWeight">
              <el-input v-model="form.fWeight" placeholder="请输入产品重量(g)" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模组类型" prop="fModuleType">
              <el-select v-loadmore="fModuleLoad" v-model="form.fModuleId" placeholder="请选择" :disabled="isEdit == 1">
                <el-option v-for="(item, index) in fModuleList" :key="index" :label="item.fModuleName"
                  :value="item.fId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通用质检波形" prop="fWaveName">
              <el-input v-model="form.fWaveName" @focus="openWave" placeholder="请输入通用质检波形" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品尺寸" prop="fProductSize">
              <el-input v-model="form.fProductSize" placeholder="请输入模组类型" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否启用" prop="fForbidStatus">
          <el-radio-group v-model.number="form.fForbidStatus" :disabled="isEdit == 1">
            <el-radio v-for="dict in fForbidStatus" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="grid-content bg-purple-light">
          <el-form-item prop="fProductUrl" label="上传标准图片">只能上传jpg/png文件，且不超过500kb
            <!-- <img :src="form.fProductUrl" v-if="form.fProductUrl"
              @click="dialogImageUrl = form.fProductUrl;  dialogVisible = true;"> -->
            <ImageUpload :value="form.fProductUrl" :limit="1" :isShowTip="false" @input="uploadFile($event)"
              :disabled="isEdit == 1">
            </ImageUpload>
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="fRemark">
          <el-input v-model="form.fRemark" type="textarea" placeholder="请输入内容" :disabled="isEdit == 1" />
        </el-form-item><br>
        <el-col :span="24">
          <el-form-item prop="bcmProBatchEntryList">
            <el-button type="primary" @click="addBatch" v-if="isEdit != 1">新增批次号</el-button><br>
            <el-table v-loading="loading" :data="form.bcmProBatchEntryList" @selection-change="handleSelectionChange">
              <el-table-column label="批次号" align="center" prop="fBatchNo" />
              <el-table-column label="添加日期" align="center" prop="fCreateDate" />
              <el-table-column label="备注" prop="fRemark" />
              <el-table-column fixed="right" label="操作" min-width="100" v-if="isEdit != 1">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit"
                    @click="handleUpdates(scope.row, 1, scope.$index)" v-hasPermi="['system:edit']"
                    v-if="isEdit != 1">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeletes(scope.row)"
                    v-hasPermi="['system:remove']" v-if="isEdit != 1">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <!-- <el-button type="primary" plain  size="mini" @click="handleAdds"></el-button> -->
        <!-- </el-form-item><br> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isEdit != 1">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>

        <el-dialog title="选择波形" :visible.sync="dialogWaveVisibles" append-to-body width="80%">
          <addWave @closeWave="closeWave" @confirmWave="confirmWave"></addWave>
        </el-dialog>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>

    <el-dialog :title="titles" :visible.sync="dialogFormVisible" append-to-body width="30%">
      <el-form v-if="dialogFormVisible" ref="gridDataForm" :model="gridData" :rules="gridDataRules" label-width="130px">
        <el-form-item label="批次号" prop="fBatchNo">
          <el-input v-model="gridData.fBatchNo" placeholder="请输入" :disabled="isEdit == 1" />
        </el-form-item>

        <el-form-item label="备注" prop="fRemark">
          <el-input v-model="gridData.fRemark" placeholder="请输入" :disabled="isEdit == 1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addData" v-if="isEdit != 1">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/basicData/product";
import { wanPreset } from "@/api/basicData/preset";
import addWave from './components/addWave.vue';
export default {
  name: "Product",
  dicts: ['sys_normal_disable'],
  components: {
    addWave
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      isEdit: 0,
      // 初始化为不禁用
      uploadDisabled: false,
      gridData: {},
      opens: false,
      // 加载状态
      loading: true,
      // 选中的 ID 数组
      ids: [],
      // 单个禁用状态
      single: true,
      // 多个禁用状态
      multiple: true,
      // 显示搜索条件状态
      showSearch: true,
      // 总条数
      total: 0,
      // 产品列表数据
      productList: [],
      // 对话:框标题
      title: "",
      titles: "",
      // 对话框显示状态
      open: false,
      dateRange: "",
      dialogFormVisible: false,
      dialogFormVisibles: false,
      dialogWaveVisibles: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fDeviceModel: undefined,
        fProductName: undefined,
        status: undefined
      },
      // 表单数据
      form: {
        fDeviceModel: undefined,
        fProductName: undefined,
        bcmProBatchEntryList: [],
        fForbidStatus: 0
      },
      // 表单校验规则
      rules: {
        fProductName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        fDeviceModel: [
          { required: true, message: "产品型号不能为空", trigger: "blur" }
        ],
        fForbidStatus: [
          { required: true, message: "请选择是否启用不能选空", trigger: "change" }
        ],
      },
      fForbidStatus: [
        { value: 0, label: '启用' },
        { value: 1, label: '停用' }
      ],
      fModuleWhere: { pageNum: 1, pageSize: 20 },
      fModuleList: [],
      gridDataRules: {
        fBatchNo: [
          { required: true, message: "批次号不能为空", trigger: "blur" }
        ]
      },
      pcType: 0,
      selectIndex: 0
    };
  },
  created() {
    // 创建时获取产品列表
    this.getList();
  },
  methods: {
    fModuleLoad() {
      this.fModuleWhere.pageNum += 1
      this.getFactory()
    },
    getFactory() {
      wanPreset(this.fModuleWhere).then(res => {
        this.fModuleList = [...this.fModuleList, ...res.rows]
      })
    },
    closeDialog() {
      this.fModuleWhere.pageNum = 1
      this.fModuleList = []
    },
    uploadFile(e) {
      this.form.fProductUrl = e
    },
    openWave() {
      this.dialogWaveVisibles = true
    },
    closeWave() {
      this.dialogWaveVisibles = false;

    },
    confirmWave(e) {
      this.dialogWaveVisibles = false;
      this.form.fWaveId = e.fId
      this.form.fWaveName = e.fWaveName
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 添加日期范围到查询参数
    addDateRange(params, dateRange) {
      params.fCreateDateStart = dateRange[0];
      params.fCreateDateEnd = dateRange[1];
      return params;
    },
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      // 调用 API 获取列表数据
      listProduct(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    // 取消操作
    cancel() {
      this.open = false;
      this.handleAdds = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fId: undefined,
        fDeviceModel: undefined,
        fProductName: undefined,
        productSort: 0,
        status: "0",
        remark: undefined,
        bcmProBatchEntryList: [],
        fForbidStatus: 0
      },
        this.fModuleWhere = 1
      this.fModuleList = [],
        this.resetForm("form");
    },
    /** 搜索操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置搜索条件 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 处理多选框选择变化
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增产品操作 */
    handleAdd() {
      this.isEdit = 0
      this.reset();
      this.getFactory();
      this.open = true;
      this.title = "新增产品";
    },
    // handleAdds() {
    //   this.reset();
    //   this.titles = "新增批次号";
    //   this.opens = true;

    // },
    /** 修改产品操作 */
    handleUpdate(row, type) {
      this.isEdit = type
      this.uploadDisabled = true;
      this.reset();
      this.getFactory();
      const fId = row.fId || this.ids
      // 获取产品详情
      getProduct(fId).then(response => {
        this.form = response.data;
        this.form.fWaveId = response.data.wfWaveForm ? response.data.wfWaveForm.fId : ''
        this.form.fWaveName = response.data.wfWaveForm ? response.data.wfWaveForm.fWaveName : ''
        this.open = true;
        if (type === 1) {
          this.open = true;
          this.title = "查看产品";
        } else {
          this.open = true;
          this.title = "修改产品";
        }
      });
    },
    // // 查看产品操作
    // handleCheck(row) {
    //   console.log(row)

    //   this.opens = true;
    //   this.title = "查看产品";

    //   this.form = { ...row };
    //   this.form.fWaveId = row.wfWaveForm.fId
    //   this.form.fWaveName = row.wfWaveForm.fWaveName
    // },
    /** 批次号修改操作 */
    handleUpdates(row, pcType, index) {
      this.gridData = { ...row };
      this.dialogFormVisible = true;
      this.selectIndex = index
      this.pcType = pcType
      this.titles = "修改批次号";
    },
    addBatch() {
      this.dialogFormVisible = true;
      this.pcType = 0;
      this.titles = '新增批次号';
      this.gridData = {
        fBatchNo: '',
        fRemark: ''
      }
    },
    // 删除批次号
    handleDeletes(row) {
      const index = this.form.bcmProBatchEntryList.findIndex(item => item.fBatchNo === row.fBatchNo);
      if (index !== -1) {
        this.form.bcmProBatchEntryList.splice(index, 1);
      }
    },
    addData: function () {
      this.$refs["gridDataForm"].validate(valid => {
        if (valid) {
          if (this.pcType === 1) {
            // 更新已有项
            const updatedItem = {
              ...this.form.bcmProBatchEntryList[this.selectIndex],
              fBatchNo: this.gridData.fBatchNo,
              fRemark: this.gridData.fRemark
            };
            // this.form.bcmProBatchEntryList[this.selectIndex] = updatedItem;
            this.$set(this.form.bcmProBatchEntryList, this.selectIndex, updatedItem);
            this.dialogFormVisible = false;
          } else {
            // 新增项
            const newItem = { ...this.gridData };
            this.form.bcmProBatchEntryList.push(newItem);
            this.dialogFormVisible = false;
          }
          // 重置表单
          this.$refs.gridDataForm.resetFields();
        }
      });

    },
    /** 提交表单操作 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fId != undefined) {
            // 调用更新 API
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 调用新增 API
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除产品操作 */
    handleDelete(row) {
      const productIds = row.fId || this.ids;
      this.$modal.confirm('是否确认删除产品编号为"' + productIds + '"的数据项？').then(function () {
        // 调用删除 API
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出操作 */
    handleExport() {
      this.download('system/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>